#include "napi/native_api.h"
#include "uart/include/native_module.h"
#include <hilog/log.h>

#undef LOG_DOMAIN
#undef LOG_TAG
#define LOG_DOMAIN 0x3200 // 全局domain宏，标识业务领域
#define LOG_TAG "MY_TAG"  // 全局tag宏，标识模块日志tag

static napi_value Add(napi_env env, napi_callback_info info)
{

    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    double value0;
    napi_get_value_double(env, args[0], &value0);

    double value1;
    napi_get_value_double(env, args[1], &value1);

    napi_value sum;
    napi_create_double(env, value0 + value1, &sum);

    return sum;
}

static napi_value Uart_test(napi_env env, napi_callback_info info) {

    size_t argc = 1;
    napi_value args[1] = {nullptr};
    
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    size_t length = 0;
//     napi_status status = napi_get_value_string_utf8(env, args[0], nullptr, 0, &length);
//     if(status != napi_ok){
//         return nullptr;
//     }
//     char* buf = new char[length + 1];
//     std::memset(buf, 0, length+1);
    char buf[32];
    napi_get_value_string_utf8(env, args[0], buf, sizeof(buf), &length);

    //OH_LOG_INFO(LOG_APP, " args[0]: %{public}s", buf);
    int ret = uart_send(buf);
    napi_value sum;
    napi_create_int32(env, ret, &sum);

    return sum;
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    char dev[] = "/dev/ttyS3";

    napi_property_descriptor desc[] = {
        {"add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"uart_send", nullptr, Uart_test, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"registerCallback", nullptr, RegisterCallback, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"unregisterCallback", nullptr, UnregisterCallback, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"callFunction", nullptr, CallFunction, nullptr, nullptr, nullptr, napi_default, nullptr},

    };
    uart_init(dev);
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}
